﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using SyncCommon;
using System.Reflection;
using System.Collections;
using SyncCommon.DAL;
using HefaSyncTool.Controls;

namespace HefaSyncTool.SyncManager
{
    public class SyncStatus
    {
        public int rowID;
        public ISyncHouse synchandler;
        public RequestType currentRequestType;
        public Thread syncThread;
        public bool IsRun = false;
        public string Url = "";
    }

    public class SyncCenter
    {
        private SyncForm uiForm;
        public HouseInfo HouseInfor;
        private ThreadSafeDictionary<long, SyncStatus> SyncRepository = new ThreadSafeDictionary<long, SyncStatus>();
        public SyncCenter(SyncForm form)
        {
            uiForm = form;
        }

        public static bool CheckLogin(long websiteID,string user,string password)
        {
            ISyncHouse syncHandler = ISyncFactory.Create(websiteID,user,password);
            try
            {
                return syncHandler.CheckLogin();
            }
            catch(Exception exp)
            {
                LogCenter.Log("登陆失败", exp);
            }
            return false;
        }
        public bool CheckIsSend()
        {
            foreach (KeyValuePair<long, SyncStatus> pair in SyncRepository)
            {
                SyncStatus statu = pair.Value;
                if (statu.syncThread != null)
                {
                    if (statu.IsRun)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public void RestoreStatus()
        {
            lock (this)
            {
                SyncRepository.Clear();
                //SharedVal.WebSites[]
                foreach (KeyValuePair<long, SDWebsite> pair in SharedVal.WebSites)
                {
                    if (!pair.Value.IsValid || !pair.Value.IsStart)
                    {
                        continue;
                    }
                    HousePost post = HousePost.SingleOrDefault("WHERE HefaCode=@0 and WebSiteID=@1 order by ID desc", this.HouseInfor.HefaCode, pair.Key);
                    int rowID = 0;
                    string url ="";
                    if (post == null)
                    {
                        rowID = uiForm.AddNewRow("", pair.Value.Name,pair.Value.IsRefresh);
                    }
                    else
                    {
                        rowID = uiForm.AddNewRow(UtilMethod.GetOpStatus((RequestType)post.RequestType, post.IsSucess ?? false), pair.Value.Name, 100, post.IsSucess ?? false, post.Status, post.Url, pair.Value.IsRefresh, (RequestType)post.RequestType);
                        url = post.Url;
                    }
                    ISyncHouse syncHandler = ISyncFactory.Create(pair.Key, pair.Value.UserName, pair.Value.Password);
                    syncHandler.UpdateStatus += new UpdateStatusHandler(syncHandler_UpdateStatus);
                    syncHandler.ValidationCode += new ValidationCodeHandler(syncHandler_ValidationCode);
                    SyncRepository.Add(pair.Key, new SyncStatus() { 
                         rowID = rowID, synchandler = syncHandler, Url =url
                    });
                }
            }
        }
        public void SyncInfor(RequestType requestType, int RowID)
        {
            foreach (KeyValuePair<long, SyncStatus> sta in SyncRepository)
            {
                if (sta.Value.rowID == RowID)
                {
                    SyncInfor(requestType, sta.Key);
                    break;
                }
            }
        }

        /// <summary>
        /// 处理编辑
        /// </summary>
        /// <param name="RowID"></param>
        public bool OpenEidt(int RowID)
        {
            foreach (KeyValuePair<long, SyncStatus> sta in SyncRepository)
            {
                if (sta.Value.rowID == RowID)
                {
                    WebEditForm f = new WebEditForm();
                    f.Show();
                    f.HefaWebBrowser.StartNewWindow += new EventHandler<Controls.BrowserExtendedNavigatingEventArgs>(HefaWebBrowser_StartNewWindow);
                    return sta.Value.synchandler.OpenEidt(new WebBrowserOp(f.HefaWebBrowser, f), HouseInfor);
                }
            }
            return true;
        }

        void HefaWebBrowser_StartNewWindow(object sender, Controls.BrowserExtendedNavigatingEventArgs e)
        {
            if (!((e.NavigationContext & UrlContext.HtmlDialog) == UrlContext.HtmlDialog))
            {
                WebEditForm newForm = new WebEditForm();
                newForm.Show();
                ExtendedWebBrowser ewb = newForm.HefaWebBrowser;
                // The (in)famous application object
                e.AutomationObject = ewb.Application;
            }
        }

        public void SyncInfor(RequestType requestType,long website)
        {
            if (SyncRepository.ContainKey(website))
            {
                SyncStatus statu = SyncRepository[website];
               
                HousePost post = HousePost.SingleOrDefault("WHERE HefaCode=@0 and WebSiteID=@1 and IsSucess=1 and RequestType =@2 order by ID desc", this.HouseInfor.HefaCode, website, RequestType.Add);
                if (requestType == RequestType.Delete
                    || requestType == RequestType.Refresh)
                {
                    if (post== null || string.IsNullOrEmpty(post.TargetID))
                    {
                        return;
                    }
                }
                if (statu.syncThread != null)
                {
                    if (statu.syncThread.ThreadState == ThreadState.Running)
                    {
                        try
                        {
                            statu.syncThread.Abort();
                        }
                        catch (Exception exp)
                        {
                            LogCenter.Log(exp);
                        }
                    }
                }
                statu.currentRequestType = requestType;
                ISyncHouse syncHandler = statu.synchandler;
                Thread t = new Thread(delegate(object obj)
                    {
                        string target = "";
                        if (requestType == RequestType.Add)
                        {
                           syncHandler.AddHouse(HouseInfor, ref target);
                        }
                        if (requestType == RequestType.Delete)
                        {
                            if (obj != null && obj is HousePost)
                            {
                                syncHandler.DeleteHouse(HouseInfor, ((HousePost)obj).TargetID);
                            }
                        }
                        if (requestType == RequestType.Refresh)
                        {
                            if (obj != null && obj is HousePost)
                            {
                                syncHandler.RefreshHouse(HouseInfor, ((HousePost)obj).TargetID);
                            }
                        }
                        statu.IsRun = false;
                    });
                statu.syncThread = t;
                t.IsBackground = true;
                statu.IsRun = true;
                t.Start(post);
                
            }
        }

        public void SyncNewHouseInfo(RequestType requestType)
        {
            lock (this)
            {
                foreach (KeyValuePair<long, SyncStatus> sta in SyncRepository)
                {
                    //如果是不支持刷新，则不进行。
                    if (requestType == RequestType.Refresh)
                    {
                        if (SharedVal.WebSites.ContainsKey(sta.Key)
                            && !SharedVal.WebSites[sta.Key].IsRefresh)
                        {
                            continue;
                        }
                    }
                    SyncInfor(requestType, sta.Key);
                }
            }
        }

       

        private string syncHandler_ValidationCode(System.Drawing.Image t)
        {
            lock(this)
            {
                return uiForm.ValidationCodeValue(t);
            }
        }

        private void syncHandler_UpdateStatus(ISyncHouse sender, StatusData statuData)
        {
            lock (this)
            {
                statuData.RowID = SyncRepository[sender.WebSiteID].rowID;
                statuData.requestType = SyncRepository[sender.WebSiteID].currentRequestType;
                if (statuData.Progress == StandardProgress.Sucess
                    || statuData.Progress == StandardProgress.Failed)
                {
                    HousePost p = new HousePost();
                    p.TargetID = statuData.TargetID;
                    p.LastTime = DateTime.Now;
                    p.HefaCode = HouseInfor.HefaCode;
                    p.TradeType = (int)HouseInfor.TradeType;
                    p.WebSiteID = sender.WebSiteID;

                    if (statuData.Progress == StandardProgress.Sucess)
                    {
                        if (statuData.requestType == RequestType.Add)
                        {
                            p.Url = statuData.Url;
                            SyncRepository[sender.WebSiteID].Url = statuData.Url;
                        }
                        if (statuData.requestType == RequestType.Delete)
                        {
                            SyncRepository[sender.WebSiteID].Url = "";
                        }
                    }
                    if (statuData.requestType == RequestType.Refresh)
                    {
                        p.Url = SyncRepository[sender.WebSiteID].Url;
                    }

                    p.Status = statuData.Status;
                    p.IsSucess = (statuData.Progress == StandardProgress.Sucess ? true : false);
                    p.RequestType = (int)statuData.requestType;
                    p.Save();
                }
                uiForm.UpdateRow(sender, statuData);
            }
        }
    }
}
